import {
	Plugin,
	Notice,
	TFile,
	App,
	ButtonComponent,
	TextComponent,
	WorkspaceLeaf,
	ItemView,
	PluginSettingTab,
	Setting,
	Modal,
	DropdownComponent,
} from "obsidian";

import { EventEmitter } from "events";

const obsidianNavigationCardTabEmitter = new EventEmitter();

import path, { join } from "path";
import { readFileSync } from "fs";

const OBFUSCATION_KEY = "obsidian-navigation-card";
const SAVE_FILE_EXTENSIONS = ".hippo";

const VIEW_TYPE_NAVIGATION_CARD = "navigation-card-tab";
const OPEN_NAVIGATION_CARD = "open-navigation-card-tab";

const DEFAULT_CATEGORY = {
	id: "default",
	label: "默认分类",
};

const ALL_CATEGORY = {
	id: "all",
	label: "全部",
};

const NOT_CATEGORY = {
	id: "not-category",
	label: "未分类",
};

interface NavigationCategoryItem {
	id: string;
	label: string;
}

interface NavigationItem {
	url: string;
	label: string;
	star: boolean;
	category: string;
}

interface ObsidianNavigationCardTabPluginSetting {
	defaultUrl: string;
	isEncrypted: boolean;
	categories: NavigationCategoryItem[];
}

const DEFAULT_SETTINGS: ObsidianNavigationCardTabPluginSetting = {
	defaultUrl: "",
	isEncrypted: false,
	categories: [
		{
			...DEFAULT_CATEGORY,
		},
	],
};

// XOR加密解密函数
function xorEncryptDecrypt(data: string, key: string): string {
	let result = [];
	for (let i = 0; i < data.length; i++) {
		const keyChar = key.charCodeAt(i % key.length);
		const dataChar = data.charCodeAt(i);
		result.push(String.fromCharCode(dataChar ^ keyChar));
	}
	return result.join("");
}

// 混淆函数
function obfuscate(data: string, isEncrypted: boolean): string {
	if (!isEncrypted) {
		return data;
	}
	return btoa(
		unescape(encodeURIComponent(xorEncryptDecrypt(data, OBFUSCATION_KEY)))
	);
}

// 解混淆函数
function deobfuscate(obfuscatedData: string, isEncrypted: boolean): string {
	if (!isEncrypted) {
		return obfuscatedData;
	}
	try {
		const decoded = decodeURIComponent(escape(atob(obfuscatedData)));
		return xorEncryptDecrypt(decoded, OBFUSCATION_KEY);
	} catch (e) {
		console.error("解混淆失败:", e);
		return "";
	}
}

function generateUUID() {
	let timestamp = new Date().getTime();
	const uuid = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(
		/[xy]/g,
		function (c) {
			const r = (timestamp + Math.random() * 16) % 16 | 0;
			timestamp = Math.floor(timestamp / 16);
			return (c === "x" ? r : (r & 0x3) | 0x8).toString(16);
		}
	);
	return uuid;
}

function getImageAsBase64(plugin: Plugin, imagePath: string): string {
	const adapter: any = plugin.app.vault.adapter;
	if (plugin.manifest && plugin.manifest.dir && adapter && adapter.basePath) {
		const imageFilePath = join(
			adapter.basePath + path.sep,
			plugin.manifest.dir,
			imagePath
		);
		const buffer = readFileSync(imageFilePath);
		const mimeType = imagePath.endsWith(".png")
			? "image/png"
			: imagePath.endsWith(".jpg") || imagePath.endsWith(".jpeg")
			? "image/jpeg"
			: imagePath.endsWith(".svg")
			? "image/svg+xml"
			: "image/*";

		return `data:${mimeType};base64,${buffer.toString("base64")}`;
	}
	return "";
}

class ConfirmModal extends Modal {
	result: boolean = false;
	message: string;

	constructor(app: App, message: string) {
		super(app);
		this.message = message;
	}

	onOpen() {
		const { contentEl, titleEl } = this;

		titleEl.createEl("h3", { text: "确认操作" });
		titleEl.className = "navigation-card-tab-category-modal-title";
		contentEl.createEl("p", { text: this.message });

		const buttons = contentEl.createDiv({ cls: "modal-button-container" });

		new ButtonComponent(buttons)
			.setButtonText("确认")
			.setWarning()
			.onClick(() => {
				this.result = true;
				this.close();
			});

		new ButtonComponent(buttons).setButtonText("取消").onClick(() => {
			this.result = false;
			this.close();
		});
	}

	onClose() {
		const { contentEl } = this;
		contentEl.empty();
	}
}

// 新增：输入模态框
class CategoryInputModal extends Modal {
	settings: ObsidianNavigationCardTabPluginSetting;
	result: string = "";
	placeholder: string;
	defaultValue: string;
	title: string;
	id: string;

	constructor(
		app: App,
		settings: ObsidianNavigationCardTabPluginSetting,
		title: string,
		placeholder: string = "",
		defaultValue: string = "",
		id: string
	) {
		super(app);
		this.title = title;
		this.placeholder = placeholder;
		this.defaultValue = defaultValue;
		this.settings = settings;
		this.id = id;
	}

	onOpen() {
		const { contentEl, titleEl } = this;

		titleEl.className = "navigation-card-tab-category-modal-title";

		titleEl.createEl("h3", { text: this.title });

		const inputContainer = contentEl.createDiv();
		const input = new TextComponent(inputContainer)
			.setPlaceholder(this.placeholder)
			.setValue(this.defaultValue);
		input.inputEl.className = "navigation-card-tab-new-win-modal-input";
		input.inputEl.focus();

		const buttons = contentEl.createDiv({ cls: "modal-button-container" });

		new ButtonComponent(buttons)
			.setButtonText("确认")
			.setCta()
			.onClick(() => {
				this.result = input.getValue().trim();
				if (!this.result.trim()) {
					new Notice("分类名称不能为空!");
					return false;
				}

				const find = this.settings.categories.find((item) => {
					return (
						item.label == this.result.trim() && item.id !== this.id
					);
				});

				if (find) {
					new Notice("该分类已存在!");
					return false;
				}

				this.close();
			});

		new ButtonComponent(buttons).setButtonText("取消").onClick(() => {
			this.result = "";
			this.close();
		});
	}

	onClose() {
		const { contentEl } = this;
		contentEl.empty();
	}
}

export default class ObsidianNavigationCardTabPlugin extends Plugin {
	settings: ObsidianNavigationCardTabPluginSetting;
	navigationCardView: NavigationCardView;

	async onload() {
		console.log("导航卡片插件已加载");

		await this.loadSettings();

		this.addSettingTab(
			new ObsidianNavigationCardTabPluginSettingTab(this.app, this)
		);

		this.registerView(VIEW_TYPE_NAVIGATION_CARD, (leaf: WorkspaceLeaf) => {
			this.navigationCardView = new NavigationCardView(this, leaf);
			return this.navigationCardView;
		});

		this.addRibbonIcon("link", "导航卡片", () => {
			this.openNavigationCardTab();
		});

		this.addCommand({
			id: OPEN_NAVIGATION_CARD,
			name: "打开导航卡片",
			callback: () => {
				this.openNavigationCardTab();
			},
		});

		this.initEvent();
	}

	onunload() {
		console.log("导航卡片插件已卸载");
		this.app.workspace.detachLeavesOfType(VIEW_TYPE_NAVIGATION_CARD);
		obsidianNavigationCardTabEmitter.removeAllListeners();
	}

	initEvent() {
		obsidianNavigationCardTabEmitter.on(
			"navigationCardTabRefreshData",
			async (selectAll) => {
				await this.loadSettings();
				await this.navigationCardView.refreshCurrentViewRender(selectAll);
			}
		);
	}

	async loadSettings() {
		this.settings = Object.assign(
			{},
			DEFAULT_SETTINGS,
			await this.loadData()
		);

		if (
			!this.settings.categories ||
			this.settings.categories.length === 0
		) {
			this.settings.categories = [
				{
					...DEFAULT_CATEGORY,
				},
			];
			await this.saveSettings();
		}
	}

	async saveSettings() {
		await this.saveData(this.settings);
	}

	async saveSettingsAndLoad() {
		this.saveSettings();
		this.loadSettings();
	}

	async openNavigationCardTab() {
		const leaves = this.app.workspace.getLeavesOfType(
			VIEW_TYPE_NAVIGATION_CARD
		);

		if (leaves.length > 0) {
			this.app.workspace.revealLeaf(leaves[0]);
			return leaves[0];
		}

		const leaf = this.app.workspace.getLeaf("tab");
		await leaf.setViewState({
			type: VIEW_TYPE_NAVIGATION_CARD,
			active: true,
		});

		this.app.workspace.revealLeaf(leaf);
		return leaf;
	}

	async addCategory(model: CategoryInputModal): Promise<boolean> {
		const category = model.result;
		if (!category.trim()) {
			new Notice("分类名称不能为空!");
			return false;
		}

		const find = this.settings.categories.find((item) => {
			return item.label == category.trim();
		});

		if (find) {
			new Notice("该分类已存在!");
			return false;
		}

		this.settings.categories.push({
			id: generateUUID(),
			label: category.trim(),
		});
		await this.saveSettings();

		obsidianNavigationCardTabEmitter.emit(
			"navigationCardTabRefreshData",
			false
		);

		new Notice(`成功添加分类!`);
		return true;
	}

	async deleteCategory(id: string): Promise<boolean> {
		if (this.settings.categories.length <= 1) {
			new Notice("至少保留一个分类");
			return false;
		}

		this.settings.categories = this.settings.categories.filter(
			(cat) => cat.id !== id
		);

		const navigationData = await this.readNavigationData();
		const updatedData = navigationData.map((item) => {
			if (item.category === id) {
				return { ...item, category: DEFAULT_CATEGORY.id };
			}
			return item;
		});

		await this.writeNavigationData(updatedData);
		await this.saveSettings();

		obsidianNavigationCardTabEmitter.emit(
			"navigationCardTabRefreshData",
			true
		);

		new Notice("成功删除分类!");
		return true;
	}

	async renameCategory(
		category: NavigationCategoryItem,
		model: CategoryInputModal
	): Promise<boolean> {
		const newName = model.result;
		if (!newName.trim()) {
			new Notice("新分类名称不能为空!");
			return false;
		}

		const find = this.settings.categories.find((item) => {
			return item.label == newName.trim();
		});

		if (find) {
			new Notice("该分类已存在!");
			return false;
		}

		const index = this.settings.categories.findIndex(
			(cat) => cat.id === category.id
		);
		if (index !== -1) {
			this.settings.categories[index] = {
				...category,
				label: newName,
			};
		}

		await this.saveSettings();

		obsidianNavigationCardTabEmitter.emit(
			"navigationCardTabRefreshData",
			false
		);
		new Notice("重命名成功！");
		return true;
	}

	async readNavigationData(): Promise<NavigationItem[]> {
		try {
			const file = this.app.vault.getAbstractFileByPath(
				"navigation-cards" + SAVE_FILE_EXTENSIONS
			);
			if (file instanceof TFile) {
				const obfuscatedData = await this.app.vault.read(file);
				const dataStr = deobfuscate(
					obfuscatedData,
					this.settings.isEncrypted
				);

				if (!dataStr) {
					new Notice("数据解混淆失败，使用空数据");
					return [];
				}

				const data = JSON.parse(dataStr);
				const processedData = Array.isArray(data)
					? data
							.map((item) => ({
								...item,
								category: item.category || DEFAULT_CATEGORY.id,
							}))
							.filter(this.validateItem)
					: [];
				return processedData;
			}
			await this.writeNavigationData([]);
			return [];
		} catch (e) {
			new Notice("读取数据失败: " + (e as Error).message);
			return [];
		}
	}

	async writeNavigationData(data: NavigationItem[]) {
		try {
			const content = JSON.stringify(
				data.filter(this.validateItem),
				null,
				2
			);

			const obfuscatedContent = obfuscate(
				content,
				this.settings.isEncrypted
			);

			const file = this.app.vault.getAbstractFileByPath(
				"navigation-cards" + SAVE_FILE_EXTENSIONS
			);

			if (file instanceof TFile) {
				await this.app.vault.modify(file, obfuscatedContent);
			} else {
				await this.app.vault.create(
					"navigation-cards" + SAVE_FILE_EXTENSIONS,
					obfuscatedContent
				);
			}
		} catch (e) {
			new Notice("保存数据失败: " + (e as Error).message);
		}
	}

	private validateItem(item: any): item is NavigationItem {
		return (
			typeof item === "object" &&
			typeof item.label === "string" &&
			typeof item.url === "string" &&
			typeof item.star === "boolean" &&
			typeof item.category === "string"
		);
	}
}

class NavigationCardView extends ItemView {
	plugin: ObsidianNavigationCardTabPlugin;
	navigationData: NavigationItem[] = [];
	filteredData: NavigationItem[] = [];
	searchTerm: string = "";
	selectedCategory: string = ALL_CATEGORY.id;
	private cardsContainer: HTMLElement;
	private categoryFilterContainer: HTMLElement;
	private categoryButtons: HTMLElement;

	constructor(plugin: ObsidianNavigationCardTabPlugin, leaf: WorkspaceLeaf) {
		super(leaf);
		this.plugin = plugin;
	}

	getViewType() {
		return VIEW_TYPE_NAVIGATION_CARD;
	}

	getDisplayText() {
		return "导航卡片";
	}

	async onOpen() {
		this.containerEl.empty();
		this.containerEl.addClass("navigation-card-tab");

		this.renderToolbar();
		this.renderCategoryFilter();
		this.renderCardContainer();
		await this.refreshDataAndRender();
	}

	async onClose() {}

	async refreshCurrentViewRender(selectAll: boolean) {
		if (selectAll) {
			this.selectedCategory = ALL_CATEGORY.id;
		}
		this.renderCategoryFilter();
		await this.refreshDataAndRender();
	}

	renderToolbar() {
		const toolbar = this.containerEl.createDiv({
			cls: "navigation-card-tab-toolbar",
		});

		const buttonContainer = toolbar.createDiv({
			cls: "navigation-card-tab-toolbar-left",
		});

		new ButtonComponent(buttonContainer)
			.setButtonText("添加新导航")
			.setCta()
			.onClick(() => {
				this.addNavigationItem(null);
			})
			.buttonEl.addClass("navigation-card-tab-toolbar-add-button");

		new ButtonComponent(buttonContainer)
			.setButtonText("打开新导航")
			.onClick(() => {
				const url = this.plugin.settings.defaultUrl;
				if (url && url.length) {
					window.open(url, "_blank");
				} else {
					this.openNewWinTab();
				}
			})
			.buttonEl.addClass("navigation-card-tab-toolbar-open-win-button");

		const searchContainer = toolbar.createDiv({
			cls: "navigation-card-tab-toolbar-right",
		});

		new TextComponent(searchContainer)
			.setPlaceholder("请输入标签或链接进行搜索...")
			.onChange((value) => {
				this.searchTerm = value.toLowerCase();
				this.filterData();
			})
			.inputEl.addClass("navigation-card-tab-toolbar-search-input");

		searchContainer.createEl("span", {
			cls: "navigation-card-tab-toolbar-search-icon",
		});
	}

	renderCategoryFilter() {
		if (this.categoryButtons) {
			while (this.categoryButtons.firstChild) {
				this.categoryButtons.removeChild(
					this.categoryButtons.firstChild
				);
			}
		} else {
			this.categoryButtons = this.containerEl.createDiv({
				cls: "navigation-card-tab-category-buttons",
			});
		}

		this.createCategoryButton(this.categoryButtons, ALL_CATEGORY);

		this.plugin.settings.categories.forEach((category) => {
			this.createCategoryButton(this.categoryButtons, category);
		});
	}

	private createCategoryButton(
		container: HTMLElement,
		category: NavigationCategoryItem
	) {
		const button = container.createEl("button", {
			cls: `navigation-card-tab-category-button ${
				this.selectedCategory === category.id ? "active" : ""
			}`,
			text: category.label,
		});

		button.onclick = () => {
			container
				.querySelectorAll(".navigation-card-tab-category-button")
				.forEach((btn) => {
					btn.classList.remove("active");
				});
			button.classList.add("active");
			this.selectedCategory = category.id;
			this.filterData();
		};
	}

	updateCategoryFilter() {
		if (this.categoryFilterContainer) {
			this.categoryFilterContainer.remove();
			this.renderCategoryFilter();
		}
	}

	renderCardContainer() {
		this.cardsContainer = this.containerEl.createDiv({
			cls: "navigation-card-tab-cards-container",
		});
	}

	async refreshDataAndRender() {
		await this.loadNavigationData();
		this.filterData();
	}

	async loadNavigationData() {
		this.navigationData = await this.plugin.readNavigationData();
	}

	sortData() {
		this.filteredData.sort((a, b) => {
			if (a.star && !b.star) return -1;
			if (!a.star && b.star) return 1;
			return a.label.localeCompare(b.label, "zh-CN");
		});
	}

	filterData() {
		let tempData =
			this.selectedCategory === ALL_CATEGORY.id
				? [...this.navigationData]
				: this.navigationData.filter(
						(item) => item.category === this.selectedCategory
				  );

		this.filteredData = this.searchTerm
			? tempData.filter(
					(item) =>
						item.label.toLowerCase().includes(this.searchTerm) ||
						item.url.toLowerCase().includes(this.searchTerm) ||
						item.category.toLowerCase().includes(this.searchTerm)
			  )
			: tempData;

		this.sortData();
		this.renderCards();
	}

	renderCards() {
		this.cardsContainer.empty();

		if (this.filteredData.length === 0) {
			this.cardsContainer.className =
				"navigation-card-tab-cards-container-empty";
			const emptyImg = getImageAsBase64(this.plugin, "assets/empty.svg");

			const emptyContainer = this.cardsContainer.createDiv({
				cls: "navigation-card-tab-cards-container-empty",
			});

			if (emptyImg) {
				emptyContainer.createEl("img", {
					cls: "navigation-card-tab-empty-img",
					attr: {
						src: emptyImg,
					},
				});
			}

			emptyContainer.createDiv({
				cls: "navigation-card-tab-empty-label",
				text: "暂无数据",
			});

			return;
		} else {
			this.cardsContainer.className =
				"navigation-card-tab-cards-container";
		}

		this.filteredData.forEach((item) => {
			const card = this.cardsContainer.createDiv({
				cls: "navigation-card-tab-navigation-card",
			});

			if (item.star) {
				card.addClass("starred");
			}

			card.createDiv({
				text: item.label,
				cls: "navigation-card-tab-navigation-card-label",
				attr: {
					title: item.label,
					style: "white-space: nowrap; overflow: hidden; text-overflow: ellipsis;",
				},
			});

			card.createDiv({
				text: item.url,
				cls: "navigation-card-tab-navigation-card-url",
				attr: {
					title: item.url,
					style: "white-space: nowrap; overflow: hidden; text-overflow: ellipsis;",
				},
			});

			const footer = card.createDiv({
				cls: "navigation-card-tab-navigation-card-footer",
			});

			const findCategory = this.plugin.settings.categories.find(
				(category) => {
					return category.id == item.category;
				}
			);

			if (!findCategory) {
				item.category = "";
			}

			footer.createDiv({
				text: findCategory ? findCategory.label : NOT_CATEGORY.label,
				cls: "navigation-card-tab-navigation-card-category",
				attr: {
					title: findCategory
						? findCategory.label
						: NOT_CATEGORY.label,
				},
			});

			const actions = footer.createDiv({
				cls: "navigation-card-tab-navigation-card-actions",
			});

			const starButton = actions.createEl("button", {
				cls: `navigation-card-tab-star-button ${
					item.star ? "active" : ""
				}`,
				attr: { title: item.star ? "取消星标" : "标为星标" },
				text: "★",
			});
			starButton.onclick = async (e) => {
				e.stopPropagation();
				item.star = !item.star;
				await this.plugin.writeNavigationData(this.navigationData);
				await this.refreshDataAndRender();
				new Notice(item.star ? "已标为星标" : "已取消星标");
			};

			const editButton = actions.createEl("button", {
				cls: "navigation-card-tab-edit-button",
				attr: { title: "编辑" },
				text: "✎",
			});
			editButton.onclick = (e) => {
				e.stopPropagation();
				this.addNavigationItem(item);
			};

			const deleteButton = actions.createEl("button", {
				cls: "navigation-card-tab-delete-button",
				attr: { title: "删除" },
				text: "✕",
			});
			deleteButton.onclick = async (e) => {
				e.stopPropagation();
				const modal = new ConfirmModal(
					this.app,
					`确定要删除"${item.label}"吗?`
				);
				modal.open();

				await new Promise((resolve) => {
					modal.onClose = () => resolve(null);
				});

				if (modal.result) {
					this.navigationData = this.navigationData.filter(
						(i) => !(i.label === item.label && i.url === item.url)
					);
					await this.plugin.writeNavigationData(this.navigationData);
					await this.refreshDataAndRender();
					new Notice("删除成功");
				}
			};

			card.onclick = () => window.open(item.url, "_blank");
		});
	}

	async addNavigationItem(item: NavigationItem | null) {
		this.containerEl
			.querySelectorAll(".navigation-card-tab-edit-overlay")
			.forEach((el) => el.remove());

		let original = {};
		if (item) {
			original = { ...item };
		}

		const overlay = this.containerEl.createDiv({
			cls: "navigation-card-tab-edit-overlay",
		});
		overlay.onclick = (e) => e.stopPropagation();

		const modal = overlay.createDiv({
			cls: "navigation-card-tab-edit-modal",
		});
		modal.createEl("h3", { text: item ? "编辑导航" : "添加新导航" });

		const form = modal.createEl("form");

		const labelGroup = form.createDiv({
			cls: "navigation-card-tab-edit-modal-form-group",
		});
		labelGroup.createEl("label", {
			cls: "navigation-card-tab-edit-modal-label",
			text: "标签:",
			attr: { for: "new-label" },
		});
		const labelInput = labelGroup.createEl("input", {
			type: "text",
			cls: "navigation-card-tab-edit-modal-input",
			value: item && item.label ? item.label : "",
			attr: {
				required: "true",
				tabIndex: "1",
				placeholder: "请输入标签名称!",
			},
		});
		labelInput.id = "new-label";
		labelInput.focus();

		const urlGroup = form.createDiv({
			cls: "navigation-card-tab-edit-modal-form-group",
		});
		urlGroup.createEl("label", {
			cls: "navigation-card-tab-edit-modal-label",
			text: "链接:",
			attr: { for: "new-url" },
		});
		const urlInput = urlGroup.createEl("input", {
			type: "url",
			cls: "navigation-card-tab-edit-modal-input",
			value: item && item.url ? item.url : "",
			attr: {
				required: "true",
				tabIndex: "2",
				placeholder: "请输入链接地址!",
			},
		});
		urlInput.id = "new-url";

		const categoryGroup = form.createDiv({
			cls: "navigation-card-tab-edit-modal-form-group",
		});
		categoryGroup.createEl("label", {
			cls: "navigation-card-tab-edit-modal-label",
			text: "分类:",
			attr: { for: "new-category" },
		});
		const categorySelect = categoryGroup.createEl("select", {
			cls: "navigation-card-tab-edit-modal-select",
			attr: {
				tabIndex: "3",
			},
		});
		categorySelect.id = "new-category";

		this.plugin.settings.categories.forEach((category) => {
			const option = categorySelect.createEl("option", {
				value: category.id,
				text: category.label,
			});
			if (
				(item && item.category === category.id) ||
				(!item && category.id === DEFAULT_CATEGORY.id)
			) {
				option.selected = true;
			}
		});

		const starGroup = form.createDiv({
			cls: "navigation-card-tab-edit-modal-star-form-group",
		});
		const starLabel = starGroup.createEl("label", {
			cls: "navigation-card-tab-edit-modal-start-label",
			text: "星标:",
			attr: { for: "new-star" },
		});
		const starInput = starGroup.createEl("input", {
			type: "checkbox",
			attr: { tabIndex: "4" },
		});
		starInput.id = "new-star";
		if (item) {
			starInput.checked = item.star;
		}

		const buttons = form.createDiv({
			cls: "navigation-card-tab-edit-modal-button-group",
		});

		const saveBtn = buttons.createEl("button", {
			cls: "mod-cta",
			text: "保存",
			type: "submit",
		});

		const cancelBtn = buttons.createEl("button", {
			text: "取消",
			type: "button",
		});

		if (item) {
			cancelBtn.onclick = () => {
				Object.assign(item, original);
				overlay.remove();
			};
		} else {
			cancelBtn.onclick = () => overlay.remove();
		}

		form.onsubmit = async (e) => {
			e.preventDefault();
			try {
				new URL(urlInput.value);
			} catch {
				new Notice("无效的链接（必须包含 http:// 或 https://）");
				urlInput.focus();
				return;
			}

			if (item) {
				item.label = labelInput.value;
				item.url = urlInput.value;
				item.star = starInput.checked;
				item.category = categorySelect.value;

				await this.plugin.writeNavigationData(this.navigationData);
				overlay.remove();
				await this.refreshDataAndRender();
				new Notice("更新成功!");
			} else {
				this.navigationData.push({
					label: labelInput.value,
					url: urlInput.value,
					star: starInput.checked,
					category: categorySelect.value,
				});

				await this.plugin.writeNavigationData(this.navigationData);
				overlay.remove();
				await this.refreshDataAndRender();
				new Notice("添加成功!");
			}
		};

		[
			labelInput,
			urlInput,
			categorySelect,
			starInput,
			cancelBtn,
			saveBtn,
		].forEach((el) => {
			el.onmousedown = (e) => e.stopPropagation();
			el.onfocus = (e) => e.stopPropagation();
		});
	}

	async openNewWinTab() {
		this.containerEl
			.querySelectorAll(".navigation-card-tab-new-win-overlay")
			.forEach((el) => el.remove());

		const overlay = this.containerEl.createDiv({
			cls: "navigation-card-tab-new-win-overlay",
		});
		overlay.onclick = (e) => e.stopPropagation();

		const modal = overlay.createDiv({
			cls: "navigation-card-tab-new-win-modal",
		});
		modal.createEl("h3", { text: "打开新导航" });

		const form = modal.createEl("form");

		const urlGroup = form.createDiv({
			cls: "navigation-card-tab-new-win-modal-form-group",
		});
		urlGroup.createEl("label", {
			cls: "navigation-card-tab-new-win-modal-label",
			text: "链接:",
			attr: { for: "nav-url" },
		});
		const urlInput = urlGroup.createEl("input", {
			type: "url",
			cls: "navigation-card-tab-new-win-modal-input",
			value: "",
			attr: {
				required: "true",
				tabIndex: "1",
				placeholder: "请输入链接地址!",
			},
		});
		urlInput.id = "nav-url";

		const buttons = form.createDiv({
			cls: "navigation-card-tab-new-win-modal-button-group",
		});

		const saveBtn = buttons.createEl("button", {
			cls: "mod-cta",
			text: "打开",
			type: "submit",
		});

		const cancelBtn = buttons.createEl("button", {
			text: "取消",
			type: "button",
		});

		cancelBtn.onclick = () => overlay.remove();

		form.onsubmit = async (e) => {
			e.preventDefault();
			try {
				new URL(urlInput.value);
			} catch {
				new Notice("无效的链接（必须包含 http:// 或 https://）");
				urlInput.focus();
				return;
			}
			window.open(urlInput.value, "_blank");
			overlay.remove();
		};

		[urlInput, cancelBtn, saveBtn].forEach((el) => {
			el.onmousedown = (e) => e.stopPropagation();
			el.onfocus = (e) => e.stopPropagation();
		});
	}
}

class ObsidianNavigationCardTabPluginSettingTab extends PluginSettingTab {
	plugin: ObsidianNavigationCardTabPlugin;

	constructor(app: App, plugin: ObsidianNavigationCardTabPlugin) {
		super(app, plugin);
		this.plugin = plugin;
	}

	display(): void {
		const { containerEl } = this;
		containerEl.empty();
		containerEl.createEl("h2", { text: "导航卡片页签设置" });

		// URL 配置
		new Setting(containerEl)
			.setName("默认链接地址")
			.setDesc(
				"打开新导航时默认打开的链接地址（必须以 http/https 开头），不设置则在使用时手动输入"
			)
			.addText((text) => {
				const textInput = text
					.setPlaceholder("https://www.baidu.com/")
					.setValue(this.plugin.settings.defaultUrl);

				const inputEl = textInput.inputEl;

				inputEl.addEventListener("blur", async () => {
					const value = inputEl.value;

					if (value && value.length) {
						try {
							new URL(value);
						} catch {
							new Notice(
								"无效的链接（必须包含 http:// 或 https://）"
							);
							return;
						}
					}

					this.plugin.settings.defaultUrl = value;
					await this.plugin.saveSettings();
					new Notice("保存配置成功");
				});

				return textInput;
			});

		// 分类管理
		const categoryTieleRow = containerEl.createDiv({
			cls: "navigation-card-tab-setting-title-row",
		});

		categoryTieleRow.createEl("h2", { text: "分类管理" });

		const categoryTieleRowBtn = categoryTieleRow.createEl("button", {
			text: "添加分类",
			cls: "navigation-card-tab-setting-add-btn",
		});

		categoryTieleRowBtn.addEventListener("click", async () => {
			const modal = new CategoryInputModal(
				this.app,
				this.plugin.settings,
				"添加分类",
				"请输入新的分类名称！",
				"",
				""
			);
			modal.open();

			await new Promise((resolve) => {
				modal.onClose = () => resolve(null);
			});

			if (modal.result) {
				await this.plugin.addCategory(modal);
				this.display();
			}
		});

		// 显示现有分类
		this.plugin.settings.categories.forEach(
			(category: NavigationCategoryItem, index: number) => {
				const setting = new Setting(containerEl).setName(
					category.label
				);

				if (category.id === DEFAULT_CATEGORY.id) {
					setting.controlEl.setText("默认不可编辑");
					setting.controlEl.className = "setting-item-description";
				} else {
					if (index != 1) {
						setting.addExtraButton((btn) =>
							btn
								.setIcon("lucide-arrow-up")
								.setTooltip("上移")
								.onClick(async () => {
									const previousItem =
										this.plugin.settings.categories[
											index - 1
										];
									const currentItem =
										this.plugin.settings.categories[index];
									this.plugin.settings.categories[index - 1] =
										currentItem;
									this.plugin.settings.categories[index] =
										previousItem;
									await this.plugin.saveSettings();

									this.display();

									obsidianNavigationCardTabEmitter.emit(
										"navigationCardTabRefreshData",
										false
									);
								})
						);
					}

					if (index != this.plugin.settings.categories.length - 1) {
						setting.addExtraButton((btn) =>
							btn
								.setIcon("lucide-arrow-down")
								.setTooltip("下移")
								.onClick(async () => {
									const nextItem =
										this.plugin.settings.categories[
											index + 1
										];
									const currentItem =
										this.plugin.settings.categories[index];

									this.plugin.settings.categories[index + 1] =
										currentItem;
									this.plugin.settings.categories[index] =
										nextItem;
									await this.plugin.saveSettings();
									this.display();

									obsidianNavigationCardTabEmitter.emit(
										"navigationCardTabRefreshData",
										false
									);
								})
						);
					}

					setting.addExtraButton((btn) =>
						btn
							.setIcon("pencil")
							.setTooltip("重命名")
							.onClick(async () => {
								const modal = new CategoryInputModal(
									this.app,
									this.plugin.settings,
									"重命名分类",
									"请输入新的分类名称:",
									category.label,
									category.id
								);
								modal.open();

								// 等待模态框关闭
								await new Promise((resolve) => {
									modal.onClose = () => resolve(null);
								});

								if (modal.result) {
									await this.plugin.renameCategory(
										category,
										modal
									);
									this.display();
								}
							})
					);
					setting.addExtraButton((btn) =>
						btn
							.setIcon("lucide-trash-2")
							.setTooltip("删除")
							.onClick(async () => {
								// 使用自定义确认模态框替换confirm()
								const modal = new ConfirmModal(
									this.app,
									`确定要删除分类"${category.label}"吗？`
								);
								modal.open();

								// 等待模态框关闭
								await new Promise((resolve) => {
									modal.onClose = () => resolve(null);
								});

								if (modal.result) {
									await this.plugin.deleteCategory(
										category.id
									);
									this.display();
								}
							})
					);
				}
			}
		);
	}
}
